package com.yskj.tms.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yskj.tms.alipay.AlipayConfig;
import com.yskj.tms.common.UsersById;
import com.yskj.tms.entity.ReCharge;
import com.yskj.tms.entity.ReChargeDetail;
import com.yskj.tms.service.ReChargeService;
import com.yskj.tms.wxdto.WxPayResult;
import com.yskj.tms.wxutil.WeiMaCreate;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.xml.sax.InputSource;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.PrintWriter;
import java.io.StringReader;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.yskj.tms.util.FiledUtil.parseXmlToList2;

/**
 * Created by Administrator on 2018/5/22.
 */
@Controller
public class ReChargeController {

    @Autowired
    private ReChargeService reChargeService;

    private UsersById users = new UsersById();

    @RequestMapping("/toReCharge.do")
    public ModelAndView toReChargeByQuery(HttpServletRequest request)throws Exception{
        ModelAndView mav = new ModelAndView("/personal/recharge/recharge");
        Map map = new HashMap();
        map.put("restatus",1);
        map.put("userid",users.getUserid(request));
        List<ReCharge> reChargeList = reChargeService.selectReChargeByRestatusAndUserid(map);
        ReChargeDetail reChargeDetail = reChargeService.selectReChargeDetailByUserid(users.getUserid(request));
        if (reChargeDetail==null){
            mav.addObject("resecond",0);
        }else {
            mav.addObject("resecond",reChargeDetail.getResecond());
        }
        mav.addObject("reChargeList",reChargeList);
//        mav.setViewName("/personal/recharge/recharge");
        return mav;
    }

    @RequestMapping(value = "toReChargePay.do")
    public ModelAndView toRecharge(HttpServletRequest request) throws Exception {
        return new ModelAndView("/personal/recharge/pay");
    }

//    @RequestMapping("toaliPay.do")
//    public void aliPay(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "remoney") double remoney) throws Exception {
//
//        //商户订单号，商户网站订单系统中唯一订单号，必填
//        String orderNo = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(Calendar.getInstance().getTime())+"-"+users.getUserid(request);
//        //订单名称，必填
//        String subjectName = "gksp";
//        //付款金额，必填
//        String total_fee = "" + remoney;//通过订单查询订单金额;
//        //商品描述，可空
//        String body = "yskj" + subjectName;
//        if ("money".equals(body)) {
//            body = "gkspyskj";
//        }
//
//        // 业务逻辑   发起充值
//        ReCharge reCharge = new ReCharge();
//        reCharge.setRemoney(remoney);
//        reCharge.setReordeernumber(orderNo);
//        reCharge.setRestatus(0);
//        reCharge.setRetype(0);
//        reCharge.setRetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
//        reCharge.setUserid(users.getUserid(request));
//
//        //把请求参数打包成map
//        Map<String, String> sParaTemp = new HashMap<String, String>();
//        sParaTemp.put("service", AlipayConfig.service);
//        sParaTemp.put("partner", AlipayConfig.partner);
//        sParaTemp.put("seller_id", AlipayConfig.seller_id);
//        sParaTemp.put("_input_charset", AlipayConfig.input_charset);
//        sParaTemp.put("payment_type", AlipayConfig.payment_type);
//        sParaTemp.put("notify_url", AlipayConfig.notify_url);
//        sParaTemp.put("return_url", AlipayConfig.return_url);
//        sParaTemp.put("anti_phishing_key", AlipayConfig.anti_phishing_key);
//        sParaTemp.put("exter_invoke_ip", AlipayConfig.exter_invoke_ip);
//        sParaTemp.put("out_trade_no", orderNo);
//        sParaTemp.put("subject", subjectName);
//        sParaTemp.put("total_fee", total_fee);
//        sParaTemp.put("body", body);
//        //其他业务参数根据在线开发文档，添加参数.文档地址:https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.O9yorI&treeId=62&articleId=103740&docType=1
//        //如sParaTemp.put("参数名","参数值");
//        //建立请求
//        String sHtmlText = AlipaySubmit.buildRequest(sParaTemp,"get","确认");
//        response.setHeader("Content-Type", "text/html; charset=UTF-8");
//        response.setCharacterEncoding("UTF-8");
//        PrintWriter out = response.getWriter();
//        System.out.println(sHtmlText);
//        out.println(sHtmlText);
//    }



    @RequestMapping("/towxpay.do")
    public ModelAndView weixinReceiveByQ(HttpServletRequest request,HttpServletResponse response,@RequestParam("minute") int minute) throws Exception {
        ModelAndView mav = new ModelAndView();

        String orderno = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(Calendar.getInstance().getTime()) +"-"+ users.getUserid(request);
        String money = "" + minute;//通过订单查询订单金额
        String payurl = WeiMaCreate.getCodeurl(orderno, money, "wxzf");
        String pa = "assets/web/images/wx"; // 保存路径
        String realpath = request.getSession().getServletContext().getRealPath(pa);  // 绝对路径
        if (!new File(realpath).exists()) {
            new File(realpath).mkdir();
        }
        String path =  realpath+"\\";
        String msg = WeiMaCreate.createWeima(payurl,orderno,path);
        if(msg == null){
            ReCharge reCharge = new ReCharge();
            reCharge.setRemoney(Double.parseDouble(money));
            reCharge.setResecond((int)(minute/0.2*60));
            reCharge.setReordernumber(orderno);
            reCharge.setRestatus(0);
            reCharge.setRetype(0);
            reCharge.setRetime(new Timestamp((new Date()).getTime()));
            reCharge.setUserid(users.getUserid(request));
            reChargeService.addReCharge(reCharge);
            String imagePath = "../" + pa + "/" + orderno + ".png";
            mav.addObject("wmpath", imagePath);
            mav.addObject("orderno",orderno);
            mav.setViewName("/personal/recharge/payQrcode");
        }
        return mav;

    }

    @RequestMapping("/checkstatus.do")
    @ResponseBody
    public String checkstatusByQuery(@RequestParam(value = "reordernumber")String reordernumber)throws Exception{
        Boolean flag =false;
        ReCharge reCharge = reChargeService.selectReChargeByReordernumber(reordernumber);
        if (reCharge.getRestatus()==1){
            flag =true;
        }
        return new ObjectMapper().writeValueAsString(flag);
    }


    @RequestMapping("/notifyUrl.do")
    public String weixinReceive(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.print("微信支付回调数据开始");
        String notityXml = "";
        String resXml = "";

        try {
            String inputLine;
            while ((inputLine = request.getReader().readLine()) != null) {
                notityXml = notityXml + inputLine;
            }
            request.getReader().close();
        } catch (Exception var13) {
            var13.printStackTrace();
        }

        System.out.println("接收到的报文：" + notityXml);
        Map m = parseXmlToList2(notityXml);
        WxPayResult wpr = new WxPayResult();
        wpr.setAppid(m.get("appid").toString());
        wpr.setBankType(m.get("bank_type").toString());
        wpr.setCashFee(m.get("cash_fee").toString());
        wpr.setFeeType(m.get("fee_type").toString());
        wpr.setIsSubscribe(m.get("is_subscribe").toString());
        wpr.setMchId(m.get("mch_id").toString());
        wpr.setNonceStr(m.get("nonce_str").toString());
        wpr.setOpenid(m.get("openid").toString());
        wpr.setOutTradeNo(m.get("out_trade_no").toString());
        wpr.setResultCode(m.get("result_code").toString());
        wpr.setReturnCode(m.get("return_code").toString());
        wpr.setSign(m.get("sign").toString());
        wpr.setTimeEnd(m.get("time_end").toString());
        wpr.setTotalFee(m.get("total_fee").toString());
        wpr.setTradeType(m.get("trade_type").toString());
        wpr.setTransactionId(m.get("transaction_id").toString());
        if ("SUCCESS".equals(wpr.getResultCode())) {
            resXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml> ";
            Map map = new HashMap();
            map.put("restatus",1);
            map.put("reordernumber",wpr.getOutTradeNo());
            reChargeService.updateReChargeRestatus(map);
            ReCharge reCharge = reChargeService.selectReChargeByReordernumber(wpr.getOutTradeNo());
            ReChargeDetail reChargeDetail = reChargeService.selectReChargeDetailByUserid(reCharge.getUserid());
            if (reChargeDetail == null){
                ReChargeDetail reChargeDetail1 = new ReChargeDetail();
                reChargeDetail1.setRemoney(reCharge.getRemoney());
                reChargeDetail1.setReaddtime(new Timestamp((new Date()).getTime()));
                reChargeDetail1.setRelasttime(new Timestamp((new Date()).getTime()));
                reChargeDetail1.setResecond(reCharge.getResecond());
                reChargeDetail1.setRechargetype(0);
                reChargeDetail1.setUserid(reCharge.getUserid());
                reChargeService.saveReChargeDetail(reChargeDetail1);
            }else{
                reChargeDetail.setResecond(reChargeDetail.getResecond()+reCharge.getResecond());
                reChargeDetail.setRemoney(reChargeDetail.getRemoney()+reCharge.getRemoney());
                reChargeDetail.setReaddtime(new Timestamp((new Date()).getTime()));
                reChargeDetail.setRelasttime(new Timestamp((new Date()).getTime()));
                reChargeDetail.setRechargetype(0);
                reChargeService.updateReChargeDetail(reChargeDetail);
            }
            System.out.println("微信支付成功返回---------------------");
        } else {
            resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml> ";
            System.out.println("微信支付失败返回---------------------");
        }
        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();
        System.out.println(resXml);
        System.out.println("微信支付回调数据结束");
        return null;
    }



}
